package name.huzhenbo.java.collection;

class SortedListImp {
    private SortedListItem head;
    private int length;

    public SortedListImp() {
        head = null;
        length = 0;
    }

    public SortedListItem insert(int val) {
        return _insert(val, head, null);
    }

    public int get(int loc) {
        return getItem(loc).val();
    }

    private SortedListItem _insert(int val, SortedListItem currentItem, SortedListItem previousItem) {
        if (currentItem == null || val <= currentItem.val()) {
            currentItem = new SortedListItem(val, currentItem);
            if (previousItem == null) {
                head = currentItem;
            } else {
                previousItem.setNext(currentItem);
            }
            length++;
            return currentItem;
        } else {
            return _insert(val, currentItem.next(), currentItem);
        }
    }

    private SortedListItem getItem(int loc) {
        if (loc < 0 || loc >= length) {
            return null;
        }
        SortedListItem item = head;
        for (int i = 0; i < loc && loc <= length - 1; i++) {
            item = item.next();
        }
        return item;
    }

    public SortedListIterator iterator() {
        return SortedListIterator.getInstance(head);
    }

}
